package com.jiajia.study.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiajia.common.utils.PageUtils;
import com.jiajia.common.utils.Query;
import com.jiajia.study.product.dao.BrandDao;
import com.jiajia.study.product.entity.BrandEntity;
import com.jiajia.study.product.service.BrandService;
import com.jiajia.study.product.service.CategoryBrandRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<BrandEntity> brandEntityQueryWrapper = new QueryWrapper<>();
        if(null != params &&  null != params.get("key")){
            String key = (String) params.get("key");
            brandEntityQueryWrapper.and(a->a.like("name",key)
                            .or(b->b.eq("first_letter",key))
                            .or(c->c.eq("brand_id",key))
            );

        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                brandEntityQueryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateInfoById(BrandEntity brandEntity) {
        this.updateById(brandEntity);
        categoryBrandRelationService.updateBrandByBrandId(brandEntity.getBrandId(),brandEntity.getName());
    }

}
